package android.slc.corelifecycle.vm;

import android.app.Application;
import android.slc.core.domain.VmBox;
import android.slc.core.vm.BaseViewModel;
import android.slc.corelifecycle.domain.RxVmBox;
import android.slc.rxlifecycle.SimpleLifecycleScopeProvider;

import androidx.annotation.NonNull;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;

/**
 * @author android.slc
 * @date 2020/3/12 10:09
 * @email sunlunchang@gmail.com
 */
public class RxViewModel extends BaseViewModel {
    protected SimpleLifecycleScopeProvider simpleLifecycleScopeProvider;

    public RxViewModel(@NonNull Application application) {
        super(application);
        simpleLifecycleScopeProvider = SimpleLifecycleScopeProvider.create();
    }

    public void initRxLifecycle() {
        simpleLifecycleScopeProvider.start();
    }

    /**
     * 绑定生命周期
     *
     * @param <T>
     * @return
     */
    public <T>AutoDisposeConverter<T> bindToLifecycle() {
       return AutoDispose.autoDisposable(simpleLifecycleScopeProvider);
    }

    @Override
    protected void registerVmBox(VmBox vmBox) {
        if (vmBox instanceof RxVmBox) {
            RxVmBox rxVmBox = (RxVmBox) vmBox;
            rxVmBox.setRxLifecycleDelegate(simpleLifecycleScopeProvider);
        }
        super.registerVmBox(vmBox);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        simpleLifecycleScopeProvider.stop();
    }
}
